<?php
/**
 * Created by PhpStorm.
 * User: chenjz
 * Date: 2017/11/29
 * Time: 16:26
 */
defined('BASEPATH') OR exit('No direct script access allowed');

require_once 'encrypt-userinfo/wxBizDataCrypt.php';
require_once 'Common.php';
class WxappLibrary {

    private $ci;
    public function __construct() {
        $this->ci = &get_instance();
    }

    /**
     * 解密用户信息
     * @param $code
     * @param $encryptedData
     * @param $iv
     * @return array|mixed|object 用户信息
     */
    public function encryptUserInfo($code, $encryptedData, $iv) {
        $common = new Common();
        // 加载配置文件
        $this->ci->config->load('wxapp', TRUE);
        // 获取小程序基本配置
        $appid  = $this->ci->config->item('appid', 'wxapp');
        $secret  = $this->ci->config->item('secret', 'wxapp');
        // 获取访问jscode2session接口参数
        $apiConfig = $this->ci->config->item('jscode2session', 'wxapp');
        $url = $apiConfig['url'];
        $grantType = $apiConfig['grant_type'];

        // 调用微信jscode2session接口获取openid和session_key
        $jsonStr = $common->curl($url.'?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type='.$grantType);
        // 结果集 数组格式
        $reqArr = json_decode($jsonStr, true);
        $pc = new WXBizDataCrypt($appid, $reqArr['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            return json_decode($data, true);
        }
        return null;
    }
}